export default class Response {
  #event;
  #context;
  #response = {
    mpserverlessComposedResponse: true,
    isBase64Encoded: false,
    statusCode: 200,
    headers: {
      'content-type': 'application/json',
    },
    body: '',
  };
  constructor(event, context) {
    this.#event = event;
    this.#context = context;
  }
 get isHttp() {
    const env = this.#context.env;
    if (env && env.MP_SOURCE === 'http') {
      return true;
    }
    return !!(this.#event.httpMethod && this.#event.headers);
  }
  setHeader(name = '', value = '') {
    //单值覆盖
    if (typeof name == 'string' && value) {
      this.#response.headers[name] = value;
    } else if (Object.prototype.toString.call(name) === '[object Object]') {
      this.#response.headers = name;
    } else {
      throw new Error('设置 header 错误');
    }
  }
  setStatus(code) {
    this.#response.statusCode = code;
  }
  setBody(value) {
    this.#response.body = value;
  }
 get body() {
    if (this.isHttp) {
      if(typeof this.#response.body === 'object'){
        this.#response.body = JSON.stringify(this.#response.body);
      }
      return this.#response;
    }
    return this.#response.body;
  }
}
